package com.huobao.shangjia_version.activitys;

import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.jjobes.slidedatetimepicker.SlideDateTimeListener;
import com.github.jjobes.slidedatetimepicker.SlideDateTimePicker;
import com.huobao.yunying.activitys.Act_SelectArea;
import com.huobao.yunying.base.HuobaoBaseActivity;
import com.huobao.yunying.entity.Banks;
import com.huobao.yunying.entity.Renzheng_Geren_Detail;
import com.huobao.yunying.entity.Renzheng_Qiye_Detail;
import com.huobao.yunying.https.Http;
import com.huobao.yunying.https.HttpConst;
import com.huobao.yunying.https.HttpListener;
import com.huobao.yunying.https.HttpUtil;
import com.huobao.yunying.utils.BitmapTools;
import com.huobao.yunying.utils.Constants;
import com.huobao.yunying.utils.ImageUtils;
import com.huobao.yunying.utils.SkipUtils;
import com.huobao.yunying.utils.UserUtils;
import com.huobao.yunying.utils.Utils;
import com.huobao.zhangying.R;

import net.bither.util.NativeUtil;

import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by Administrator on 2016/8/18.
 */
public class Act_Renzheng_Qiye extends HuobaoBaseActivity implements View.OnClickListener{

	private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	private static final int REQUEST_ZHENGMIAN = 1;
	private static final int REQUEST_SELECT_AREA = 3;
	private static final int REQUEST_SELECT_BANK = 4;
	//审核状态
	@ViewInject(R.id.tv_status)
	private TextView tv_status;
	//审核时间
	@ViewInject(R.id.tv_time)
	private TextView tv_time;
	//备注
	@ViewInject(R.id.tv_beizhu)
	private TextView tv_beizhu;
	//账户名
	@ViewInject(R.id.edt_name)
	private EditText edt_name;
	//门店名称
	@ViewInject(R.id.edt_store_name)
	private EditText edt_store_name;
	//企业全称
	@ViewInject(R.id.edt_true_name)
	private EditText edt_true_name;
	//营业执照号码
	@ViewInject(R.id.edt_id_num)
	private EditText edt_id_num;
	//到期时间
	@ViewInject(R.id.tv_select_endtime)
	private TextView tv_select_endtime;
	//是否长期
	@ViewInject(R.id.cb_id_longtime)
	private CheckBox cb_id_longtime;
	//选择开户银行
	@ViewInject(R.id.tv_kaihuyinhang)
	private TextView tv_kaihuyinhang;
	//选择开户银行所在地
	@ViewInject(R.id.tv_kaihuyinhang_address)
	private TextView tv_kaihuyinhang_address;
	//银行账号
	@ViewInject(R.id.edt_id_bank)
	private EditText edt_id_bank;
	//正面
	@ViewInject(R.id.iv_zhengmian)
	private ImageView iv_zhengmian;
	//提交
	@ViewInject(R.id.btn_submit)
	private Button btn_submit;

	private String m_zhengmian_path;

	private int status;//-1:新增  2：重新认证
	//重新认证的头
	@ViewInject(R.id.view_update)
	private View view_update;
	private String areaid, areaname;

	@Override
	protected int getContentView() {
		return R.layout.layout_renzheng_qiye;
	}

	@Override
	protected String getTitleText() {
		return "企业实名认证";
	}

	@Override
	protected void init() {
		status = getIntent().getIntExtra("status", -1);
		if (status == -1) view_update.setVisibility(View.GONE);
		tv_select_endtime.setOnClickListener(this);
		tv_kaihuyinhang.setOnClickListener(this);
		tv_kaihuyinhang_address.setOnClickListener(this);
		iv_zhengmian.setOnClickListener(this);
		btn_submit.setOnClickListener(this);
		getUserMember();
		if (status == -1)return;
		getDetail();
	}

	private void showDetail(Renzheng_Qiye_Detail detail) {
		tv_status.setText("审核未通过");
		tv_time.setText("审核时间：" + detail.getChecktime());
		tv_beizhu.setText(detail.getRemark());
		edt_true_name.setText(detail.getCompany_name());
		edt_id_num.setText(detail.getReg_number());
		cb_id_longtime.setChecked(detail.getLong_time().equals("1") ? true : false);
		edt_id_bank.setText(detail.getBank_account());
		tv_select_endtime.setText(detail.getLong_time().equals("1") ? "长期" : detail.getEndtime_regnum());
		tv_kaihuyinhang.setText(detail.getPublic_account());
		tv_kaihuyinhang_address.setText(detail.getRegion_name());
		ImageUtils.loadimg(iv_zhengmian, detail.getLicense());

	}

	private void getDetail() {
		Map<String, String> map = HttpUtil.getParams("app", "companyapprove", "act", "view");
		Http.getInstant().sendRequest(context, map, new HttpListener() {
			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				Renzheng_Qiye_Detail detail = JSON.parseObject(jsonObject.getString("retval"), Renzheng_Qiye_Detail.class);
				showDetail(detail);
			}

			@Override
			public void onHttpError(String error) {

			}
		});
	}

	private void getUserMember() {
		Map<String, String> map = HttpUtil.getParams("app", "approve", "act", "member");
		Http.getInstant().sendRequest(context, map, new HttpListener() {
			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				jsonObject = jsonObject.getJSONObject("retval");
				String user_name = jsonObject.getString("user_name");
				String shop_name = jsonObject.getString("shop_name");
				edt_name.setText(user_name);
				edt_store_name.setText(shop_name);
				edt_name.setEnabled(false);
				edt_store_name.setEnabled(false);
			}

			@Override
			public void onHttpError(String error) {

			}
		});
	}


	@Override
	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.tv_select_endtime:
				String time = tv_select_endtime.getText().toString().trim();
				Date date = new Date();
				try {
					date = format.parse(time);
				} catch (Exception e) {
					date = new Date();
				}
				showDateDialog(date);
				break;
			case R.id.tv_kaihuyinhang:
				getBacks();
				break;
			case R.id.tv_kaihuyinhang_address:
				Intent intent = new Intent(this, Act_SelectArea.class);
				startActivityForResult(intent, REQUEST_SELECT_AREA);
				break;
			case R.id.iv_zhengmian:
				onSelectImage(REQUEST_ZHENGMIAN);
				break;
			case R.id.btn_submit:
				submit();
				break;
		}
	}

	private void submit() {
		String company_name = edt_true_name.getText().toString().trim();
		String reg_number = edt_id_num.getText().toString().trim();
		String endtime_regnum = tv_select_endtime.getText().toString().trim();
		String cy = cb_id_longtime.isChecked() ? "1" : "0";
		String bank_account = tv_kaihuyinhang.getText().toString().trim();
		String region_name = areaname;
		String region_id = areaid;
		String public_account = edt_id_bank.getText().toString().trim();
		String license = m_zhengmian_path;
		if (TextUtils.isEmpty(company_name) || TextUtils.isEmpty(reg_number)  || TextUtils.isEmpty(region_name) || TextUtils.isEmpty(region_id) || TextUtils.isEmpty(bank_account) || TextUtils.isEmpty(public_account) || TextUtils.isEmpty(license)) {
			Toast.makeText(context, "请将信息补充完整！", Toast.LENGTH_SHORT).show();
			return;
		}
		if(!cb_id_longtime.isChecked() && TextUtils.isEmpty(endtime_regnum)){
			Toast.makeText(context, "请将信息补充完整！", Toast.LENGTH_SHORT).show();
			return;
		}
		Map<String, String> map;
		if (cb_id_longtime.isChecked())
			map = HttpUtil.getParams("app", "companyapprove", "act", status == -1 ? "add" : "edit", "company_name", company_name, "reg_number", reg_number, "bank_account", bank_account, "region_name", region_name, "region_id", region_id, "public_account", public_account, "license", license, "cy", cy);
		else
			map = HttpUtil.getParams("app", "companyapprove", "act", status == -1 ? "add" : "edit", "company_name", company_name, "reg_number", reg_number, "bank_account", bank_account, "region_name", region_name, "region_id", region_id, "public_account", public_account, "license", license, "endtime_regnum", endtime_regnum);
		Http.getInstant().sendRequest(context, map, new HttpListener() {
			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				String msg = jsonObject.getString("retval");
				Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
				setResult(RESULT_OK);
				finish();
			}

			@Override
			public void onHttpError(String error) {

			}
		});
	}

	private SlideDateTimeListener listener = new SlideDateTimeListener() {

		@Override
		public void onDateTimeSet(Date date) {
			tv_select_endtime.setText(format.format(date));
		}

		@Override
		public void onDateTimeCancel() {
		}
	};

	private void showDateDialog(Date date) {
		new SlideDateTimePicker.Builder(getSupportFragmentManager()).setListener(listener).setInitialDate(date).build()
				.show();
	}

	private void onSelectImage(int requestCode) {
		Intent intent = new Intent(this, MultiImageSelectorActivity.class);
		// 是否显示拍摄图片
		intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
		// 最大可选择图片数量
		intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
		// 选择模式
		intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
		startActivityForResult(intent, requestCode);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK) return;
		switch (requestCode) {
			case REQUEST_ZHENGMIAN:
				List<String> mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
				if (mSelectPath == null || mSelectPath.size() == 0) return;
				String zhengmian = mSelectPath.get(0);
				uploadImage(zhengmian, Constants.qiyerenzheng);
				break;
			case REQUEST_SELECT_AREA:
				areaid = data.getStringExtra("id");
				areaname = data.getStringExtra("name");
				tv_kaihuyinhang_address.setText(areaname);
				break;
			case REQUEST_SELECT_BANK:
				Banks bank = (Banks) data.getSerializableExtra("data");
				tv_kaihuyinhang.setText(bank.getValue());
				break;
		}
	}


	private void uploadImage(final String path, final int type) {
		Bitmap bitmap = BitmapTools.createImageThumbnail(path);
		if (bitmap == null)
			return;
		File f = new File(path);
		File newPath = new File(f.getParent(), f.getName() + "temp" + ".jpg");
		NativeUtil.compressBitmap(bitmap, 100, newPath.getAbsolutePath(), true);
		bitmap.recycle();
		String base64str = Base64.encodeToString(Utils.File2byte(newPath.getAbsolutePath()), Base64.NO_WRAP);
		Map<String, String> map = HttpUtil.getParams("app", "uploadpic","act","picupload","type", type + "", "user_id", UserUtils.getUserid(context) + "", "portrait",
				base64str);
		Http.getInstant().sendRequest(context, true, HttpConst.UPLOAD_PHOTO_URL, map, new HttpListener() {
			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				String photo = jsonObject.getString("retval");
				switch (type) {
					case Constants.qiyerenzheng:
						m_zhengmian_path = HttpConst.UPLOAD_BASE_URL+photo;
						ImageUtils.loadimg(iv_zhengmian, "file://"+path);
						break;
				}
			}

			@Override
			public void onHttpError(String error) {

			}
		});
	}

	private void getBacks() {
		Map<String, String> map = HttpUtil.getParams("app", "companyapprove", "act", "bank");
		Http.getInstant().sendRequest(context, map, new HttpListener() {
			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				List<Banks> banks = JSON.parseArray(jsonObject.getString("retval"), Banks.class);
				SkipUtils.showSelectString(Act_Renzheng_Qiye.this, "选择银行", banks, REQUEST_SELECT_BANK, "value");
			}

			@Override
			public void onHttpError(String error) {

			}
		});
	}
}
